package com.test.platform.service.publish;

import com.test.platform.model.ExecutionStatus;
import com.test.platform.model.PublishInfo;
import com.test.platform.websocket.WebSocketMessage;
import com.test.platform.websocket.WebSocketService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Service
public class PublishNotificationService {
    private static final Logger logger = LoggerFactory.getLogger(PublishNotificationService.class);

    @Autowired
    private WebSocketService webSocketService;

    // 发送进度通知
    public void sendProgressNotification(String owner, String name, ExecutionStatus status, String message) {
        try {
            Map<String, Object> data = new HashMap<>();
            data.put("owner", owner);
            data.put("name", name);
            data.put("status", status);
            
            WebSocketMessage wsMessage = new WebSocketMessage(
                "progress",
                data,
                message
            );
            webSocketService.sendMessage("progress", wsMessage);
            logger.info("进度通知已发送: {}/{} - {} - {}", owner, name, status, message);
        } catch (Exception e) {
            logger.error("发送进度通知失败: {}/{}", owner, name, e);
        }
    }

    // 发送更新通知
    public void sendUpdateNotification(PublishInfo publishInfo) {
        try {
            String message = String.format("发布信息已更新: %s/%s", 
                publishInfo.getOwner(), publishInfo.getName());
            WebSocketMessage wsMessage = new WebSocketMessage("refresh", null, message);
            webSocketService.sendMessage("refresh", wsMessage);
            logger.info("更新通知已发送: {}", message);
        } catch (Exception e) {
            logger.error("发送更新通知失败: {}", e);
        }
    }

    // 发送确认请求并等待响应
    public CompletableFuture<Boolean> sendConfirmationRequest(String message, long timeout) {
        CompletableFuture<Boolean> future = new CompletableFuture<>();
        try {
            WebSocketMessage confirmRequest = new WebSocketMessage("confirm", null, message);
            webSocketService.sendMessage("confirm", confirmRequest);
            webSocketService.setConfirmationCallback(future::complete);
            
            // 设置超时
            return future.completeOnTimeout(false, timeout, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error("发送确认请求失败: {}", message, e);
            future.complete(false);
            return future;
        }
    }

    // 发送错误通知
    public void sendErrorNotification(String owner, String name, String errorMessage) {
        try {
            WebSocketMessage wsMessage = new WebSocketMessage(
                "error",
                Map.of(
                    "owner", owner,
                    "name", name
                ),
                errorMessage
            );
            webSocketService.sendMessage("error", wsMessage);
            logger.error("错误通知已发送: {}/{} - {}", owner, name, errorMessage);
        } catch (Exception e) {
            logger.error("发送错误通知失败: {}/{}", owner, name, e);
        }
    }

    // 发送批量操作结果通知
    public void sendBatchResultNotification(List<Map<String, Object>> results) {
        try {
            WebSocketMessage wsMessage = new WebSocketMessage(
                "batchResult",
                Map.of("results", results),
                "批量操作完成"
            );
            webSocketService.sendMessage("batchResult", wsMessage);
            logger.info("批量操作结果通知已发送，共 {} 条结果", results.size());
        } catch (Exception e) {
            logger.error("发送批量操作结果通知失败", e);
        }
    }
}